package com.irt.rootcloud.realtime.gketl.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 日志处理公用类
 * <p>Title:</p>
 * <p>Description:</p>
 * <p>Company:</p>
 * @author Ken.zhang
 * @date 2017-4-18 上午10:18:25
 */
public class LogParseTool {

	public static Map<String, Object> beanToMap(Object obj) {
		Map<String, Object> params = new HashMap<String, Object>(0);
		try {
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			PropertyDescriptor[] descriptors = propertyUtilsBean
					.getPropertyDescriptors(obj);
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (!"class".equals(name)) {
					params.put(name,
							propertyUtilsBean.getNestedProperty(obj, name));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}

	// 处理json格式日志、
	public static Map<String, String> parseJsonLog(String log, String busitype,
			String logtype, String cloumn) {
		int index = log.indexOf("#{");// json格式这样分割，因为日志内容里可能会存在#,不能靠#分割
		// 清洗的内容
		String content = log.substring(index + 1);
		Map<String, String> contentMap = jsonToMap(content, cloumn);
		return contentMap;
	}

	private static boolean isJson(String jsonstr) {
		if (!jsonstr.startsWith("{")) {
			return false;
		} else if (jsonstr.startsWith("{") && jsonstr.endsWith("}")) {
			return true;
		}
		return true;
	}

	// 解析json格式的字符串为map
	public static Map<String, String> jsonToMap(String dtjson, String cloumn) {
		String[] columns = cloumn.split(";");
		List<String> columnsList = new ArrayList<String>();
		Collections.addAll(columnsList, columns);
		Map<String, String> map = new HashMap<String, String>();
		return DiguiJsonToMap(dtjson, columnsList, map);
	}

	// 解析json格式的字符串为map
	public static Map<String, String> jsonToMap(String dtjson) {
		Map<String, String> map = new HashMap<String, String>();
		return DiguiJsonToMap(dtjson, map);
	}

	// 递归json to map
	private static Map<String, String> DiguiJsonToMap(String jsonstr,
			Map<String, String> map) {
		JSONObject jsonObject = JSONObject.parseObject(jsonstr);
		Iterator it = jsonObject.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = jsonObject.getString(key);
			boolean isjson = isJson(value);
			if (isjson) {
				DiguiJsonToMap(value, map);
			} else {
				map.put(key, value);
			}
		}
		return map;
	}

	// 递归json to map
	private static Map<String, String> DiguiJsonToMap(String jsonstr,
			List<String> columnsList, Map<String, String> map) {
		JSONObject jsonObject = JSONObject.parseObject(jsonstr);
		Iterator it = jsonObject.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = jsonObject.getString(key);
			boolean isjson = isJson(value);
			if (isjson) {
				DiguiJsonToMap(value, columnsList, map);
			} else {
				if (columnsList.contains(key)) {
					map.put(key, value);
				}
			}
		}
		return map;
	}

	// 解析map 为json格式的字符串
	public static String mapToJson(Map<String, String> map) {
		String jsontxt = null;
		if (map != null) {
			jsontxt = JSON.toJSONString(map);
		}
		return jsontxt;
	}

	// 将日志转化为对象
	public static <T> Object convLogToBean(Map<String, String> map,
			final Class<T> clazz) {
		T result = null;
		try {
			result = clazz.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				Method setMethod = pd.getWriteMethod();
				if (setMethod != null) {
					String propertyName = pd.getName();
					if (map.containsKey(propertyName)) {
						BeanUtils.setProperty(result, propertyName,
								map.get(propertyName));
					}
					// if (map.containsKey(propertyName.toLowerCase())) {
					// BeanUtils.setProperty(result, propertyName,
					// map.get(propertyName));
					// }
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将日志格式转换成每5分钟的形式
	 * 
	 * @param dateStr
	 * @return
	 */
	public static String modDate(String dateStr) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (dateStr == null || dateStr.equals("")) {
			return null;
		}
		Date date = null;
		Calendar calendar = Calendar.getInstance();
		String modDate = "";
		try {
			date = df.parse(dateStr);
			calendar.setTime(date);
			Integer min = calendar.get(Calendar.MINUTE);
			min = min + (5 - min % 5);
			calendar.set(Calendar.MINUTE, min);
			calendar.set(Calendar.SECOND, 0);
			modDate = df.format(calendar.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return modDate;
	}

	public static void main(String args[]) {
		String logs = "{\"sn\":4299,\"timeStamp\":\"2017-01-23 02:02:04\",\"status\":{\"HCU_HoleProtect\":0,\"HCU_PlateLiftHeight\":60000,\"HCU_Back\":0,\"PCU_LoftModeButton\":0,\"HCU_ForkHight\":0,\"PCU_DriveModeButton\":1,\"HCU_ProductNO\":52701005,\"HCU_Down\":1,\"GPRS_SigStrength\":3,\"HCU_LockPW\":12345,\"PCU_BuzzerStatus\":1,\"PCU_HandleMStatus\":1,\"GPS_Velocity\":2.2,\"HCU_WorkMode\":1,\"GPS_StarsNum\":2,\"Bat_Volume\":2,\"Bat_CRCurrent\":80,\"HCU_DeviceNO\":666666,\"PCU_HandleHRButton\":0,\"Reserved8\":0,\"Reserved9\":0,\"GPS_SigStrength\":1,\"Bat_WorkStatus\":1,\"Bat_CRStatus\":2,\"HCU_ProductTypeID\":235,\"Reserved1\":0,\"Alarm_ErrorCode\":30,\"Reserved3\":0,\"Reserved2\":0,\"GPS_Orientation\":1.1,\"Reserved5\":0,\"Reserved4\":0,\"Reserved7\":0,\"Reserved6\":12,\"Bat_ChargeInputV\":88,\"HCU_DeviceHWVer\":235,\"HCU_HorAngleX\":10,\"HCU_HorAngleY\":10,\"HCU_DeviceSWVer\":235,\"GPS_Longitude\":112.29399,\"HCU_DriveMode\":2,\"PCU_HandleEnableButton\":1,\"Bat_ChargeCurrent\":80,\"Timestamp_Local\":\"2017-01-20 14:21:53.652\",\"HCU_TurnL\":1,\"Bat_Temperature\":118,\"HCU_Lift\":1,\"HCU_LockStatus\":8,\"Bat_LiquidLevel\":80,\"HCU_LockMode\":1,\"Timestamp_CloudM2M\":\"2017-01-23 14:02:04.896\",\"PCU_BellButton\":0,\"Bat_RechargeCurrent\":808,\"HCU_TurnR\":1,\"HCU_ProductTypeName\":2,\"Bat_V\":6000,\"HCU_WorkTime\":6578,\"HCU_ForkLow\":1,\"GPS_Latitude\":35.406403,\"HCU_Pressure\":400,\"GPRS_EMEI\":\"1234567891234560\",\"HCU_YearMonthDay\":16,\"HCU_Forward\":0,\"PCU_LowVBell\":1,\"PCU_HandleHLButton\":0,\"PCU_HandleSimValue\":126,\"Reserved10\":0,\"Reserved11\":0,\"HCU_Load\":500},\"transFlag\":1,\"deviceId\":\"10000029_666666\"}";
		Map<String, String> mm = jsonToMap(logs);
		System.out.println(mm.size());
	}
}
